

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="MEUSA">
  <meta name="keywords" content="">
  <title>力扣每日一题 2020年10月31日 - MBLOG</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/railscasts.min.css" />
    
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.2.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>MBLOG</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/img/bg2.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container page-header text-center fade-in-up">
            <span class="h2" id="subtitle">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2020-10-31 17:15" pubdate>
        2020年10月31日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      865 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      11
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto" id="post">
            <!-- SEO header -->
            <h1 style="display: none">力扣每日一题 2020年10月31日</h1>
            
            <div class="markdown-body" id="post-body">
              <h1 id="力扣每日一题-2020年10月31日"><a href="#力扣每日一题-2020年10月31日" class="headerlink" title="力扣每日一题 2020年10月31日"></a>力扣每日一题 2020年10月31日</h1><h4 id="381-O-1-时间插入、删除和获取随机元素-允许重复"><a href="#381-O-1-时间插入、删除和获取随机元素-允许重复" class="headerlink" title="381. O(1) 时间插入、删除和获取随机元素 - 允许重复"></a><a target="_blank" rel="noopener" href="https://leetcode-cn.com/problems/insert-delete-getrandom-o1-duplicates-allowed/">381. O(1) 时间插入、删除和获取随机元素 - 允许重复</a></h4><blockquote>
<p>从今天起打算记录一下每日一题，来督促自己学习，结果没想到第一天就来个困难呢（</p>
</blockquote>
<div class="hljs"><pre><code class="hljs reasonml">设计一个支持在平均 时间复杂度 <span class="hljs-constructor">O(1)</span> 下， 执行以下操作的数据结构。

注意: 允许出现重复元素。

insert(<span class="hljs-keyword">val</span>)：向集合中插入元素 <span class="hljs-keyword">val</span>。
remove(<span class="hljs-keyword">val</span>)：当 <span class="hljs-keyword">val</span> 存在时，从集合中移除一个 <span class="hljs-keyword">val</span>。
getRandom：从现有集合中随机获取一个元素。每个元素被返回的概率应该与其在集合中的数量呈线性相关。</code></pre></div>

<div class="hljs"><pre><code class="hljs yaml"><span class="hljs-string">示例:</span>

<span class="hljs-string">//</span> <span class="hljs-string">初始化一个空的集合。</span>
<span class="hljs-string">RandomizedCollection</span> <span class="hljs-string">collection</span> <span class="hljs-string">=</span> <span class="hljs-string">new</span> <span class="hljs-string">RandomizedCollection();</span>

<span class="hljs-string">//</span> <span class="hljs-string">向集合中插入</span> <span class="hljs-number">1</span> <span class="hljs-string">。返回</span> <span class="hljs-literal">true</span> <span class="hljs-string">表示集合不包含</span> <span class="hljs-number">1</span> <span class="hljs-string">。</span>
<span class="hljs-string">collection.insert(1);</span>

<span class="hljs-string">//</span> <span class="hljs-string">向集合中插入另一个</span> <span class="hljs-number">1</span> <span class="hljs-string">。返回</span> <span class="hljs-literal">false</span> <span class="hljs-string">表示集合包含</span> <span class="hljs-number">1</span> <span class="hljs-string">。集合现在包含</span> [<span class="hljs-number">1</span>,<span class="hljs-number">1</span>] <span class="hljs-string">。</span>
<span class="hljs-string">collection.insert(1);</span>

<span class="hljs-string">//</span> <span class="hljs-string">向集合中插入</span> <span class="hljs-number">2</span> <span class="hljs-string">，返回</span> <span class="hljs-literal">true</span> <span class="hljs-string">。集合现在包含</span> [<span class="hljs-number">1</span>,<span class="hljs-number">1</span>,<span class="hljs-number">2</span>] <span class="hljs-string">。</span>
<span class="hljs-string">collection.insert(2);</span>

<span class="hljs-string">//</span> <span class="hljs-string">getRandom</span> <span class="hljs-string">应当有</span> <span class="hljs-number">2</span><span class="hljs-string">/3</span> <span class="hljs-string">的概率返回</span> <span class="hljs-number">1</span> <span class="hljs-string">，1/3</span> <span class="hljs-string">的概率返回</span> <span class="hljs-number">2</span> <span class="hljs-string">。</span>
<span class="hljs-string">collection.getRandom();</span>

<span class="hljs-string">//</span> <span class="hljs-string">从集合中删除</span> <span class="hljs-number">1</span> <span class="hljs-string">，返回</span> <span class="hljs-literal">true</span> <span class="hljs-string">。集合现在包含</span> [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>] <span class="hljs-string">。</span>
<span class="hljs-string">collection.remove(1);</span>

<span class="hljs-string">//</span> <span class="hljs-string">getRandom</span> <span class="hljs-string">应有相同概率返回</span> <span class="hljs-number">1</span> <span class="hljs-string">和</span> <span class="hljs-number">2</span> <span class="hljs-string">。</span>
<span class="hljs-string">collection.getRandom();</span></code></pre></div>



<p>初看这题的第一反应就想到了哈希表（因为要求插入、查询、删除的平均时间复杂度在o(1)下），但一开始有一个没想通的就是允许重复然后随机获取概率与其数量相关。后来看到说用List维护数据，哈希表维护数据的Index，当删除时，将需要删除的数据与List最后一个数据交换，避免删除List的数据造成重新排列的问题，这样就可以在o(1)的时间内完成这三个操作了。</p>
<p>于是最后完成的代码为：</p>
<div class="hljs"><pre><code class="hljs c#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">RandomizedCollection</span>
   &#123;
       <span class="hljs-keyword">public</span> List&lt;<span class="hljs-built_in">int</span>&gt; values;
       <span class="hljs-keyword">public</span> Dictionary&lt;<span class="hljs-built_in">int</span>, HashSet&lt;<span class="hljs-built_in">int</span>&gt;&gt; valuesIndex;
       <span class="hljs-comment">/** Initialize your data structure here. */</span>
       <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">RandomizedCollection</span>(<span class="hljs-params"></span>)</span> &#123;
           values = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-built_in">int</span>&gt;();
           valuesIndex = <span class="hljs-keyword">new</span> Dictionary&lt;<span class="hljs-built_in">int</span>, HashSet&lt;<span class="hljs-built_in">int</span>&gt;&gt;();
       &#125;
   
       <span class="hljs-comment">/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */</span>
       <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-built_in">bool</span> <span class="hljs-title">Insert</span>(<span class="hljs-params"><span class="hljs-built_in">int</span> val</span>)</span> &#123;
           values.Add(val);
           <span class="hljs-keyword">if</span> (valuesIndex.ContainsKey(val))
           &#123;
               valuesIndex[val].Add(values.Count - <span class="hljs-number">1</span>);
               <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
           &#125;
           <span class="hljs-keyword">else</span>
           &#123;
               valuesIndex[val] = <span class="hljs-keyword">new</span> HashSet&lt;<span class="hljs-built_in">int</span>&gt;();
               valuesIndex[val].Add(values.Count - <span class="hljs-number">1</span>);
               <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
           &#125;
       &#125;
   
       <span class="hljs-comment">/** Removes a value from the collection. Returns true if the collection contained the specified element. */</span>
       <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-built_in">bool</span> <span class="hljs-title">Remove</span>(<span class="hljs-params"><span class="hljs-built_in">int</span> val</span>)</span> &#123;
          <span class="hljs-keyword">if</span> (!valuesIndex.ContainsKey(val))
           &#123;
               <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
           &#125;
           
           <span class="hljs-keyword">if</span> (val == values.Last())
           &#123;
               valuesIndex[val].Remove(values.Count - <span class="hljs-number">1</span>);
               values.RemoveAt(values.Count - <span class="hljs-number">1</span>);
               <span class="hljs-keyword">if</span> (valuesIndex[val].Count == <span class="hljs-number">0</span>)
           	&#123;
               	valuesIndex.Remove(val);
           	&#125;
               <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
           &#125;
           <span class="hljs-built_in">int</span> index = valuesIndex[val].Last(); <span class="hljs-comment">//所要删的元素的index</span>
           <span class="hljs-built_in">int</span> lastIndex = values.Count - <span class="hljs-number">1</span>;<span class="hljs-comment">//最后一个元素的index</span>
           <span class="hljs-built_in">int</span> tmp = values[lastIndex];<span class="hljs-comment">//最后一个元素</span>
           
           valuesIndex[tmp].Remove(lastIndex);<span class="hljs-comment">//最后一个元素把index删掉</span>
           valuesIndex[tmp].Add(index);<span class="hljs-comment">//最后一个元素添加所要删除的元素的index</span>
           values[index] = tmp;<span class="hljs-comment">//将最后一个元素放到要删的元素处</span>
           values.RemoveAt(lastIndex);<span class="hljs-comment">//删除数组最后一个</span>
           valuesIndex[val].Remove(index);<span class="hljs-comment">//将删除的元素的index从其dic中删除</span>
           
           <span class="hljs-keyword">if</span> (valuesIndex[val].Count == <span class="hljs-number">0</span>)
           &#123;
               valuesIndex.Remove(val);
           &#125;
           
           <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
       &#125;
   
       <span class="hljs-comment">/** Get a random element from the collection. */</span>
       <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-built_in">int</span> <span class="hljs-title">GetRandom</span>(<span class="hljs-params"></span>)</span> &#123;
           Random random = <span class="hljs-keyword">new</span> Random(Guid.NewGuid().GetHashCode());
           <span class="hljs-keyword">return</span> values[random.Next(<span class="hljs-number">0</span>,values.Count)];
       &#125;
   &#125;</code></pre></div>

<p>其中随机数这块卡了我好久，一开始直接调用的<code> Random random = new Random();</code>结果由于时间间隔太短导致每次取得的随机值都一样，后来粗暴的将seed设成上方这样，勉强拿到了比较随机的值。</p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/LeetCode/">LeetCode</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/%E6%AF%8F%E6%97%A5%E4%B8%80%E9%A2%98/">每日一题</a>
                    
                      <a class="hover-with-bg" href="/tags/LeetCode/">LeetCode</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <article class="post-prev col-6">
                    
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2020/10/29/NavMesh/">
                        <span class="hidden-mobile">NavMesh</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>







  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '#post-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "力扣每日一题 2020年10月31日&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>















</body>
</html>
